from flask import Blueprint, render_template, request
from applications.common.utils.rights import authorize
from applications.models import Earthquake, Building
from applications.schemas import EarthOutSchema, BuildOutSchema
from applications.common.utils.http import table_api
from applications.common.curd import model_to_dicts
from applications.common.helper import ModelFilter
from applications.common.utils.validate import xss_escape


admin_earthquake = Blueprint('adminEarthquake', __name__, url_prefix='/admin/earth')

@admin_earthquake.get('/')
# @authorize("earth:info", log=True)
def earth_info():
    return render_template('admin/earthquake/earthquake.html')


#   用户分页查询
@admin_earthquake.get('/data')
# @authorize("admin:earth:main", log=True)
def data():
    # 获取请求参数
    id = request.args.get('id', type=int)
    Longitude = xss_escape(request.args.get('Longitude', type=str))
    Latitude = xss_escape(request.args.get('Latitude', type=str))
    Deep = request.args.get('Deep', type=int)
    Type = xss_escape(request.args.get('Type', type=str))
    Level = xss_escape(request.args.get('Level', type=str))
    Location = xss_escape(request.args.get('Location', type=str))


    # 查询参数构造
    mf = ModelFilter()
    if id:
        mf.exact(field_name="id", value=id)
    if Longitude:
        mf.contains(field_name="Longitude", value=Longitude)
    if Latitude:
        mf.contains(field_name="Latitude", value=Latitude)
    if Deep:
        mf.exact(field_name="Deep", value=Deep)
    if Type:
        mf.contains(field_name="Type", value=Type)
    if Level:
        mf.contains(field_name="Level", value=Level)
    if Location:
        mf.contains(field_name="Location", value=Location)


    # orm查询
    # 使用分页获取data需要.items
    earth = Earthquake.query.filter(mf.get_filter(model=Earthquake)).layui_paginate()
    count = earth.total
    # 返回api
    return table_api(data=model_to_dicts(schema=EarthOutSchema, data=earth.items), count=count)


#   用户分页查询
@admin_earthquake.get('/building')
# @authorize("admin:building:main", log=True)
def building():
    # 获取请求参数
    id = request.args.get('id', type=int)
    Name = xss_escape(request.args.get('Name', type=str))
    Num = request.args.get('Num', type=int)
    People1 = xss_escape(request.args.get('People1', type=str))
    People2 = xss_escape(request.args.get('People2', type=str))


    # 查询参数构造
    mf = ModelFilter()
    if id:
        mf.exact(field_name="id", value=id)
    if Name:
        mf.contains(field_name="Name", value=Name)
    if Num:
        mf.exact(field_name="Num", value=id)
    if People1:
        mf.contains(field_name="People1", value=People1)
    if People2:
        mf.contains(field_name="Location", value=People2)


    # orm查询
    # 使用分页获取data需要.items
    build = Building.query.filter(mf.get_filter(model=Building)).layui_paginate()
    count = build.total
    # 返回api
    return table_api(data=model_to_dicts(schema=BuildOutSchema, data=build.items), count=count)
